<?php

namespace App\Http\Middleware;


use App\Http\Controllers\WebApi\Business\AuthBusiness;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

class ApiAuth
{
    public function handle($req, \Closure $next)
    {
        $token = $req->header('token');//对用户进行权限校验
        $userInfo = Cache::get($token);
        $userInfo = json_decode($userInfo,true);
        if(!$userInfo) {
            return errBack('登录已过期,请重新登录', 401);
        }
        $userInfo['token'] = $token;
        $req->userInfo = $userInfo;
        //校验接口请求权限
        $permission = $this->checkPermission($userInfo['role_id']);
        if(!$permission){
//            return errBack('没有接口访问权限');//此处的 error_code 不能和 token 过期混淆, 执行的操作不一样
        }
        return $next($req);
    }

    //请求权限校验
    public function checkPermission($role_id)
    {
        $auth = new AuthBusiness();
        $opAuth = $auth->operationAuth($role_id)->toArray();//操作权限
        $action = Route::current()->getActionName();
        $uri = Route::current()->uri();
        foreach ($opAuth as $value){
            if($action == $value['auth_code']){
                return true;
            }
        }
        return false;
    }
}
